package resources

import (
	"github.com/jinzhu/gorm"
	"time"
)

//CREATE TABLE `machines` (
//`id` bigint NOT NULL AUTO_INCREMENT,
//`ip` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
//`cpu` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
//`cpu_core` int DEFAULT NULL,
//`memory` int DEFAULT NULL,
//`volume` int DEFAULT NULL COMMENT '数据盘大小单位G',
//`status` tinyint(1) DEFAULT NULL,
//`created_at` datetime DEFAULT NULL,
//`updated_at` datetime DEFAULT NULL,
//mac_addr varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
//`volume_device` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
//PRIMARY KEY (`id`)
//) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

type Machines struct {
	Id           int64     `json:"id" gorm:"primary_key;column:id"`
	Ip           string    `json:"ip" gorm:"column:ip"`
	Cpu          string    `json:"cpu" gorm:"column:cpu"`
	CpuCore      int       `json:"cpu_core" gorm:"column:cpu_core"`
	Memory       int       `json:"memory" gorm:"column:memory"`
	Volume       int       `json:"volume" gorm:"column:volume"`
	Status       int       `json:"status" gorm:"column:status"`
	CreatedAt    time.Time `json:"created_at" gorm:"column:created_at"`
	UpdatedAt    time.Time `json:"updated_at" gorm:"column:updated_at"`
	MacAddr      string    `json:"mac_addr" gorm:"column:mac_addr"`
	VolumeDevice string    `json:"volume_device" gorm:"column:volume_device"`
	Port         int       `json:"port" gorm:"column:port"`
}

func (c *Machines) TableName() string {
	return "machines"
}

func (c *Machines) Create(db *gorm.DB) error {
	return db.Create(c).Error
}
func (c *Machines) CreateOrUpdate(db *gorm.DB) error {
	//db.Where("mac_addr = ?", c.MacAddr).First(c)
	//return db.Create(c).Error
	return db.Where("mac_addr = ?", c.MacAddr).Assign(c).FirstOrCreate(c).Error
}
func (c *Machines) Update(db *gorm.DB) error {
	return db.Update(c).Error
}
func (c *Machines) GetById(db *gorm.DB) error {
	return db.Where("id = ?", c.Id).First(c).Error
}
func (c *Machines) FindByIp(db *gorm.DB) error {
	return db.Where("ip = ?", c.Ip).First(c).Error
}
func (c *Machines) GetList(db *gorm.DB, offset int, limit int, search map[string]interface{}) ([]Machines, int, error) {
	var list []Machines
	var total int
	query := db.Model(&Machines{})
	if search != nil {
		for k, v := range search {
			query = query.Where(k+" = ?", v)
		}
	}
	query.Count(&total)
	query.Offset(offset).Limit(limit).Find(&list)
	return list, total, query.Error
}
